//
//  IMTCANMessageAnalyser.m
//  ROCOMO
//
//  Created by Kyle Sun on 5/17/16.
//  Copyright © 2016 ROCOMO. All rights reserved.
//

#import "IMTCANMessageAnalyser.h"

@interface IMTCANMessageAnalyser()

@property (nonatomic, strong) NSMutableData *dataPool;

@end

@implementation IMTCANMessageAnalyser

- (NSData *)messageDataFromData:(NSData *)data {
    
    //  缓存大于1000字节时重新初始化
    if (!self.dataPool || self.dataPool.length > 1000) {
        self.dataPool = [[NSMutableData alloc] init];
    }
    
    [self.dataPool appendData:data];
    
    NSInteger head = 0;
    NSInteger tail = 0;
    
    NSUInteger length = self.dataPool.length;
    Byte *bytes = (Byte *)malloc(length);
    [self.dataPool getBytes:bytes length:length];
    
    BOOL firstAA = NO;
    BOOL successAA = NO;
    BOOL first55 = NO;
    BOOL success55 = NO;
    for (int i = 0; i < length; i++) {
        Byte byte = bytes[i];
        if (byte == 0xAA) {
            if (firstAA) {
                head = i-1;
                successAA = YES;
            } else {
                firstAA = YES;
            }
        } else {
            firstAA = NO;
        }
        
        if (successAA) {
            if (byte == 0x55) {
                if (first55) {
                    tail = i;
                    success55 = YES;
                    first55 = NO;
                    break;
                } else {
                    if (i > 1 && bytes[i-1] == 0xA5 && bytes[i-2] != 0xA5) {
                        first55 = NO;
                    } else {
                        first55 = YES;
                    }
                }
            } else {
                first55 = NO;
            }
        }
    }
    free(bytes);
    
    NSData *messageData = nil;
    if (successAA && success55) {
        long length = tail-head+1;
        messageData = [self.dataPool subdataWithRange:NSMakeRange(head, length)];
        if (tail+1 < self.dataPool.length) {
            NSData *remainingData = [self.dataPool subdataWithRange:NSMakeRange(length, self.dataPool.length - length)];
            self.dataPool = [NSMutableData dataWithData:remainingData];
        } else {
            self.dataPool = [[NSMutableData alloc] init];
        }
    }
    
    return messageData;
}

@end

